<!doctype html>
<html lang="zh-CN">
<head>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width,initial-scale=1" />
	<title>相册管理</title>
    <link rel="stylesheet" href="/css/style.css">
	<!-- <link rel="stylesheet" href="style.css"> -->
</head>
<body>
<div class="page">
	<!-- 新增导航栏 -->
	<nav style="background:var(--card);border-radius:12px;padding:18px;box-shadow:var(--shadow);min-width:180px;display:flex;gap:18px;align-items:center;margin-bottom:24px;">
		<button class="btn ghost" id="navPhoto" onclick="showSection('photo')">图片管理</button>
		<button class="btn ghost" id="navComment" onclick="showSection('comment')">评论管理</button>
	</nav>
	<div id="sectionPhoto">
		<div class="admin-panel">
			<h2 class="title" id="album-title">相册标题</h2>
			<div class="stats">
				<div>
					<span class="muted">类别：</span>
					<span id="album-category">-</span>
				</div>
				<button class="btn ghost" id="rename-btn">重命名</button>
				<button class="btn ghost" id="change-category-btn">更改类别</button>
				<button class="btn admin-mini-btn" id="delete-album-btn">删除相册</button>
			</div>
			<hr style="margin:18px 0;">
			<div>
				<h3 style="margin-bottom:8px;">图片列表</h3>
				<div id="photo-list" style="display:flex;flex-wrap:wrap;gap:14px;"></div>
				<div style="margin-top:18px;">
					<input type="file" id="upload-input" multiple accept="image/*" style="display:none;">
					<button class="btn" id="upload-btn">上传照片</button>
				</div>
			</div>
		</div>
	</div>
	<div id="sectionComment" style="display:none;">
		<div class="admin-panel">
			<h2 class="title">评论管理</h2>
			<div id="comment-list" style="margin-top:18px;"></div>
		</div>
	</div>
</div>

<!-- 重命名弹窗 -->
<div class="overlay hidden" id="rename-modal">
	<div class="modal" style="max-width:400px;">
		<div class="right">
			<h3>重命名相册</h3>
			<input type="text" id="rename-input" class="field" placeholder="输入新标题">
			<div style="margin-top:12px;">
				<button class="btn" id="confirm-rename">确定</button>
				<button class="btn ghost" id="cancel-rename">取消</button>
			</div>
		</div>
	</div>
</div>
<!-- 更改类别弹窗 -->
<div class="overlay hidden" id="category-modal">
	<div class="modal" style="max-width:400px;">
		<div class="right">
			<h3>更改类别</h3>
			<select id="category-select" class="field"></select>
			<div style="margin-top:12px;">
				<button class="btn" id="confirm-category">确定</button>
				<button class="btn ghost" id="cancel-category">取消</button>
			</div>
		</div>
	</div>
</div>

<script>
// 获取albumId（可从URL参数获取，实际部署时建议用路由参数）
function getAlbumId() {
  const pathMatch = location.pathname.match(/albummanagement\/(\w+)/);
  return pathMatch ? pathMatch[1] : '1';
}


const albumId = getAlbumId();
// 权限校验整合到fetchAlbumInfo

// 获取相册信息
async function fetchAlbumInfo() {
	const res = await fetch(`/getalbuminfo/${albumId}`);
	if (!res.ok) return null;
	const albumInfo = await res.json();
	// 权限校验：只有管理员或相册作者可访问
	const userRes = await fetch('/getuserinfo');
	const userInfo = await userRes.json();
	console.log(userInfo);
	console.log(albumInfo);
	if (userInfo.role !== '管理员' && userInfo.userid !== albumInfo.authorId) {
		alert('无权限访问此页面');
		window.location.href = '/main';
		return null;
	}
	return albumInfo;
}

// 获取类别列表
async function fetchCategoryList() {
	const res = await fetch('/getcategorylist');
	if (!res.ok) return [];
	return await res.json();
}

// 渲染相册信息
async function renderAlbum() {
	//延迟500毫秒以确保数据更新
	await new Promise(r => setTimeout(r, 500));
	const info = await fetchAlbumInfo();
	if (!info) return;
	document.getElementById('album-title').textContent = info.title || '-';
	document.getElementById('album-category').textContent = info.category || '-';
	renderPhotos(info.photos || []);
}

// 渲染图片列表
function renderPhotos(photos) {
	const list = document.getElementById('photo-list');
	list.innerHTML = '';
	photos.forEach(photo => {
		const photoId = photo.photoId || photo.id || '';
		const fileUrl = photo.fileUrl || photo.url || '';
		const thumb = document.createElement('div');
		thumb.className = 'album-card';
		thumb.style.width = '180px';
		thumb.innerHTML = `
			<img src="${fileUrl}?t=${Date.now()}" alt="photo" style="height:120px;object-fit:cover;">
			<div class="meta">
				<span class="info">ID: ${photoId}</span>
				<button class="admin-mini-btn" data-id="${photoId}" style="margin-right:8px;">删除</button>
				<button class="admin-mini-btn" data-id="${photoId}" style="background:#e7f7ff;color:#2196f3;border:1px solid #bde3ff;">设为封面</button>
			</div>
		`;
		// 删除按钮事件
		thumb.querySelector('button').onclick = () => deletePhoto(photoId);
		// 设为封面按钮事件
		thumb.querySelectorAll('button')[1].onclick = () => setCover(photoId);
		list.appendChild(thumb);
	});
}

function setCover(photoId) {
	// 这里预留设为封面接口，实际需后端支持
	fetch('/setcover', {
		method: 'POST',
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify({ albumId, photoId })
	});
	renderAlbum();
}

// 上传照片
document.getElementById('upload-btn').onclick = () => {
	document.getElementById('upload-input').click();
};
document.getElementById('upload-input').onchange = async function() {
    const files = Array.from(this.files);
    if (!files.length) return;
    fetch('/uploadphotos', {
        method: 'POST',
        body: (() => {
            const formData = new FormData();
            formData.append('albumId', albumId);
            files.forEach(file => formData.append('photos', file));
            return formData;
        })()
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            renderAlbum();
        } else {
            alert('上传失败');
        }
    });
};

// 删除照片
function deletePhoto(photoId) {
	if (confirm('确定要删除该照片吗？')) {
		fetch('/deletephoto', {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ albumId, photoId })
		});
		renderAlbum();
	}
}

// 重命名相册
document.getElementById('rename-btn').onclick = () => {
	document.getElementById('rename-modal').classList.remove('hidden');
};
document.getElementById('cancel-rename').onclick = () => {
	document.getElementById('rename-modal').classList.add('hidden');
};
document.getElementById('confirm-rename').onclick = async () => {
	const newTitle = document.getElementById('rename-input').value.trim();
	if (!newTitle) return alert('请输入新标题');
	fetch('/renamealbum', {
		method: 'POST',
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify({ albumId, newTitle })
	});
	document.getElementById('rename-modal').classList.add('hidden');
	renderAlbum();
};

// 更改类别
document.getElementById('change-category-btn').onclick = async () => {
	const select = document.getElementById('category-select');
	select.innerHTML = '';
	const categories = await fetchCategoryList();
	categories.forEach(cat => {
		const opt = document.createElement('option');
		opt.value = cat;
		opt.textContent = cat;
		select.appendChild(opt);
	});
	document.getElementById('category-modal').classList.remove('hidden');
};
document.getElementById('cancel-category').onclick = () => {
	document.getElementById('category-modal').classList.add('hidden');
};
document.getElementById('confirm-category').onclick = async () => {
	const newCat = document.getElementById('category-select').value;
	fetch('/changealbumcategory', {
		method: 'POST',
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify({ albumId, newCategory: newCat })
	});
	document.getElementById('category-modal').classList.add('hidden');
	renderAlbum();
};

// 删除相册
document.getElementById('delete-album-btn').onclick = () => {
	if (confirm('确定要删除整个相册吗？')) {
		fetch('/deletealbum', {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ albumId })
		});
		location.href = '/main'; // 删除后返回主页面
	}
};



// 渲染评论列表
async function renderComments() {
	const res = await fetch('/getcomments', {
		method: 'POST',
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify({ albumId })
	});
	let data = await res.json();
	let comments = Array.isArray(data.comments) ? data.comments : [];
	const list = document.getElementById('comment-list');
	list.innerHTML = '';
	comments.forEach(c => {
		const div = document.createElement('div');
		div.style = 'padding:8px 0;border-bottom:1px dashed #e6eef8;display:flex;align-items:center;gap:12px;';
		div.innerHTML = `
			<span style="font-size:12px;color:#888;">ID:${c.id || ''}</span>
			<strong>${c.user}</strong>
			<span class='muted' style='font-size:13px;'>${c.text}</span>
			<span class='muted' style='font-size:11px;'>${c.ts}</span>
		`;
		// 删除按钮
		const delBtn = document.createElement('button');
		delBtn.className = 'admin-mini-btn';
		delBtn.textContent = '删除';
		delBtn.onclick = function() {
			if (confirm('确定要删除该评论吗？')) {
				fetch('/deletecomment', {
					method: 'POST',
					headers: { 'Content-Type': 'application/json' },
					body: JSON.stringify({ commentId: c.id })
				}).then(() => renderComments());
			}
		};
		div.appendChild(delBtn);
		list.appendChild(div);
	});
}

// 区块切换逻辑
function showSection(section) {
	document.getElementById('sectionPhoto').style.display = (section === 'photo') ? '' : 'none';
	document.getElementById('sectionComment').style.display = (section === 'comment') ? '' : 'none';
	document.getElementById('navPhoto').classList.toggle('active', section === 'photo');
	document.getElementById('navComment').classList.toggle('active', section === 'comment');
	if (section === 'comment') {
		renderComments();
	}
}

// 初始化渲染
showSection('photo');
renderAlbum();
</script>
</body>
</html>
